<?php
/***
 * 发行人
 */
namespace app\api\controller;

use app\api\controller\BaseController;

class KycController extends BaseController{
    /**
	*
    *详情
	**/
	public function getApplyDetail(){
       
        $token			= (input('post.token')) ? input('post.token') : '';	
        
        if(!$token){
            return json(['code'=>0,'code_dec'=>'用户信息不存在']);
        }
		$where = 'a.status != -1 ';
      
		if($token){
            $userArr = explode(',',auth_code($token,'DECODE'));
			$uid = $userArr[0];
			$where.=" and b.id=$uid";
        }
        $data	= db('realname_auth')->alias('a')
        ->field('a.card_up,a.card_down,a.status,a.remarks,b.username,b.realname')
        ->join('users b','a.uid=b.id','left')
        ->where($where)
        ->find();
       
        //p($where);
        if(empty($data)){
            return json(['code'=>0,'code_dec'=>'您还没有申请']);
        }

        $data['card_up']=$data['card_up']?($_SERVER['REQUEST_SCHEME'].'://'.$_SERVER['HTTP_HOST'].$data['card_up']):'';
        $data['card_down']=$data['card_down']?($_SERVER['REQUEST_SCHEME'].'://'.$_SERVER['HTTP_HOST'].$data['card_down']):'';

        $statusArr=$this->getStatus();   
	
        $data['statusStr']=$statusArr[$data['status']];

		return json(['code'=>1,'data'=>$data]);
	}
	/**
	*
    *申请
	**/
	public function apply(){
        $token			= request()->param('token','','trim') ;	
        
        if(!$token){
            return ['code'=>0,'code_dec'=>'用户信息不存在'];
        }
        $data['uid']=0;
		if($token){
			$userArr = explode(',',auth_code($token,'DECODE'));
           
			$data['uid'] = $userArr[0];
		}
        $data['realname'] = request() ->param('realname','','trim');
        $data['card_up'] = str_replace($_SERVER['REQUEST_SCHEME'].'://'.$_SERVER['HTTP_HOST'],'',request()->param('card_up','','trim')) ;
        $data['card_down'] = str_replace($_SERVER['REQUEST_SCHEME'].'://'.$_SERVER['HTTP_HOST'],'',request()->param('card_down','','trim')) ;
  
        //数据验证
       
		$validate = validate('app\api\validate\Kyc');
		if(!$validate->scene('add')->check($data)){
			//抛出异常
			return json(['code'=>0,'code_dec'=>$validate->getError()]);
		}
        $data['create_time']=time();
        $data['status']=1;

        $info	= db('realname_auth')->alias('a')
        ->where(['uid'=>$data['uid']])
        ->find();
        if(!empty($info)&&$info['status']==2){
            return json(['code'=>0,'code_dec'=>'您已经实名认证过']);
        }
        //p($data);
        if($info){
            db('realname_auth')->where(['id'=>$info['id']])->update($data);
        }else{
            db('realname_auth')->insert($data);
        }
		return json(['code'=>1,'data'=>[],'code_dec'=>'success']);
	}
   
    
    /**
	 * Undocumented function
	 *
	 * @return void
	 */
	private function getStatus(){
		return [
			1=>'审核中',
			2=>'审核通过',
			3=>'审核失败'
		];
	}



}
